package com.suray.wcs.service.robot;

import com.suray.basic.wcs.plc.pojo.CargoReady;
import com.suray.basic.wcs.plc.pojo.Robot;
import com.suray.basic.wcs.plc.pojo.RobotHeartBaseResult;
import com.suray.basic.wcs.plc.pojo.TaskSend;
import com.suray.commin.core.redis.RedisCache;
import com.suray.commin.core.utils.SpringContextHolder;
import com.suray.wcs.res.service.rescontact.ActionOrder;
import com.suray.commin.annotation.InterfaceLog;
import com.suray.wcs.service.core.util.LongConnSendUtilLora;
import com.suray.wcs.service.execption.RobotOrderExecuteException;
import com.suray.wcs.service.rescontact.ResultContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ToRobot {
    private RedisCache redisCache = SpringContextHolder.getBean(RedisCache.class);
    private Logger log = LoggerFactory.getLogger(this.getClass());
    private static final Map<Robot, ToRobot> toRobotMap = new ConcurrentHashMap<>();
    private final Robot robot;

    protected ToRobot(Robot robot) {
        this.robot = robot;
    }

    /**
     * 心跳
     *
     * @return 返回结果
     * @throws IOException 网络异常
     */
    @InterfaceLog(value = "心跳", sender = "WCS", recipient = "ROBOT", useMethod = false)
    public String heartRequest(String heartStr) throws IOException {
        log.info("发送报文：{}", heartStr);
        return LongConnSendUtilLora.send(heartStr,robot);
    }

    public static ToRobot getInstance(Robot robot) {
        if (robot == null) {
            throw new IllegalArgumentException("机械臂对象参数为空");
        }
        ToRobot toRobot = toRobotMap.get(robot);
        if (toRobot == null) {
            toRobot = new ToRobot(robot);
            toRobotMap.put(robot, toRobot);
        }
        return toRobot;
    }

    /**
     * 接收命令执行结束信号
     *
     * @param sendTime
     * @return
     */
    @InterfaceLog(value = "saveInterfaceLog.toRes.receiveResult", sender = "WCS", recipient = "ROBOT")
    private Integer receiveResult(Integer wcsTaskNo, ActionOrder actionOrder, long sendTime) throws IOException {
        log.info(robot.getName() + "开始等待命令结束信号,当前命令：" + actionOrder.getCommandNo());
        while (true) {
            LongConnSendUtilLora.recevie(robot);
            /*HeartBaseResult receiverResult = ResultContainer.getContainer(rgv).getResult(actionOrder.getCommandNo());
            if (receiverResult != null && receiverResult.getRetDate().getTime() >= sendTime
                    && receiverResult.getCmdResult() != 1 && receiverResult.getCmdResult() != 2) {
                log.info(robot.getName() + "接收到命令结束信号,当前命令：" + actionOrder.getCommandNo());
                return Integer.valueOf(receiverResult.getCmdResult() != 0 ? receiverResult.getCmdResult() : 0);
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }*/
        }
    }

    /**
     * 接收命令接收到信号
     *
     * @param sendTime
     * @return
     */
    @InterfaceLog(value = "货物到位", sender = "WCS", recipient = "ROBOT")
    public boolean resReceiveResult(CargoReady cargoReady, long sendTime) {
        int count = 0;
        while (true) {
            RobotHeartBaseResult receiverResult = ResultContainer.getContainer(robot).getRobotResult(cargoReady.getCargoReadyTaskNo());
            if (receiverResult != null && receiverResult.getRetTime() >= sendTime) {
                if (receiverResult.getCargoReadyStatus() == 1) {
                    log.info(robot.getNo() + "ROBOT返回命令接收成功信号，当前命令：" + cargoReady.getCargoReadyTaskNo());
                    return true;
                } else {
                    if (count > 0 && (count % 10) == 0) {
                        //命令重发
                        int times = count / 10;
                        log.info("货物到位命令重发...，当前第{}次重发，当前命令:{}", times, cargoReady.getCargoReadyTaskNo());
                        robot.getRobotHeart().getCargoReadyCommand().offer(cargoReady);
                    } else if (count >= 52) {
                        log.info("{}指令序号{}的指令，未接收到机械臂接收任务成功，机械臂返回任务完成，数据交互可能存在丢包，检查网络是否稳定", robot.getName(), receiverResult.getCargoReadyTaskNo());
                        if (receiverResult.getCargoReadyStatus() == 0) {
                            throw new RobotOrderExecuteException(robot.getName(), receiverResult.getCargoReadyTaskNo().intValue(), "指令序号" + receiverResult.getCargoReadyTaskNo() +
                                    "的指令，未接收到机械臂接收任务成功，机械臂返回任务完成，数据交互可能存在丢包，检查网络是否稳定");
                        }
                    }
                }
            }
            if (count == 52) {
                return false;
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            count++;
        }
    }

    /**
     * 接收命令接收到信号
     *
     * @param sendTime
     * @return
     */
    @InterfaceLog(value = "任务下发", sender = "WCS", recipient = "ROBOT")
    public boolean resReceiveResult(TaskSend taskSend, long sendTime) {
        int count = 0;
        while (true) {
            RobotHeartBaseResult receiverResult = ResultContainer.getContainer(robot).getRobotResult(taskSend.getTaskSendTaskNo());
            if (receiverResult != null && receiverResult.getRetTime() >= sendTime) {
                if (receiverResult.getTaskSendStatus() == 1) {
                    log.info("{}ROBOT返回命令接收成功信号，当前命令：{}", robot.getName(), taskSend.getTaskSendTaskNo());
                    return true;
                } else {
                    if (count > 0 && (count % 10) == 0) {
                        //命令从发
                        int times = count / 10;
                        log.info("ROBOT任务下发命令重发...，当前第{}次重发，当前命令:{}",times, taskSend.getTaskSendTaskNo());
                        robot.getRobotHeart().getTaskSendCommand().offer(taskSend);
                    } else if (count >= 52) {
                        log.info("{}指令序号{}的指令，未接收到机械臂接收任务成功，机械臂返回任务完成，数据交互可能存在丢包，检查网络是否稳定！", robot.getName(), receiverResult.getTaskSendTaskNo());
                        if (receiverResult.getTaskSendStatus() == 0) {
                            throw new RobotOrderExecuteException(robot.getName(), receiverResult.getTaskSendTaskNo(), "指令序号" + receiverResult.getTaskSendStatus() +
                                    "的指令，未接收到机械臂接收任务成功，机械臂返回任务完成，数据交互可能存在丢包，检查网络是否稳定");
                        }
                    }
                }
            }
            if (count == 52) {
                return false;
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            count++;
        }
    }

    /**
     * 获取指令序号
     */
    public synchronized int getAutoIncrementNum() {
        Integer cacheObject = redisCache.getCacheObject(robot.getName());
        if (cacheObject == null) {
            redisCache.setCacheObject(robot.getName(), 2);
            return 2;
        }
        if (cacheObject == 254) {
            redisCache.setCacheObject(robot.getName(), 3);
            return 3;
        }
        redisCache.setCacheObject(robot.getName(), cacheObject + 1);
        return cacheObject + 1;
    }
}
